﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using DLM.Web.ViewModel;
using DLM.Services.Interfaces;
using DLM.Domain.Model;
using DLM.Infrastructure.Imaging;
using DLM.Infrastructure.Exception;
using DLM.Web.MVC.Extensions;
using DLM.Services.Implementations;
using DLM.Infrastructure.Logging;

namespace DLM.Web.MVC.Controllers
{
    public class UserController : Controller
    {
        private IUserService userService;
        private IPartyService partyService;
        private static string[] imageType = { "image/jpeg", "image/jpg", "image/pjpeg" };

        public UserController(IUserService userService, IPartyService partyService)
        {
            this.userService = userService;
            this.partyService = partyService;
        }

        [HttpGet]
        public ActionResult View(int? id)
        {
            UserDetailPageView pageView = new UserDetailPageView();


            pageView.User = this.userService.GetUser(id ?? 0);
            if (pageView.User != null)
            {
                pageView.EngagedParties = this.partyService.MyRecentParties(pageView.User.AccountName, 0, 6);
                ViewData["RecentParty"] = pageView.EngagedParties;
                ViewData["UserID"] = pageView.User.UserID;
                if (Request.IsAuthenticated)
                {
                    pageView.Browser = this.userService.GetUser(User.Identity.Name);
                    pageView.IsGreeted = this.userService.IsGreeted(pageView.Browser.AccountName, pageView.User.UserID);
                    pageView.HasAlbum = this.userService.HasPhoto(pageView.Browser.UserID);
                }

                if (!string.IsNullOrEmpty(pageView.User.Photo))
                {
                    pageView.Album = this.userService.GetPhotos(id ?? 0);
                }

                this.userService.AddView(id ?? 0, Request.ServerVariables["REMOTE_ADDR"].ToString());
                return View(pageView);
            }
            return View();
        }

        [HttpGet]
        public ActionResult RecentParties(int? id,int ? pageIndex)
        {
            var user = this.userService.GetUser(id ?? 0);
            var list = this.partyService.MyRecentParties(user.AccountName, pageIndex ?? 0, 10);
            return View(list);

        }

        [HttpGet]
        public ActionResult List(int? index)
        {
            //UserPageView userView = new UserPageView();
            //userView.List = this.userService.GetUser();
            var user = this.userService.GetUser();
            return View(user);
        }

        [HttpGet]
        public ActionResult Edit()
        {
            var account = this.userService.GetAccount(User.Identity.Name);
            //UserPageView userView = new UserPageView();
            //userView.User = this.userService.GetUser(id ?? 0);
            var user = this.userService.GetUserByAccount(account.AccountID);
            ViewData["UserPhoto"] = this.userService.GetPhotos(user.UserID);
            return View(user);
        }

        [HttpGet]
        [UserAuthorize]
        public ActionResult UserCenter(int? page)
        {
            if (Request.IsAjaxRequest())
            {

                BonusPageView ajaxBonusView = new BonusPageView();
                ajaxBonusView.Bonus = this.partyService.GetBonus(User.Identity.Name);
                ajaxBonusView.Log = this.partyService.GetBonusLog(User.Identity.Name, page ?? 0, 10);
                return View("_BonusInfo", ajaxBonusView);
            }
            var account = this.userService.GetAccount(User.Identity.Name);
            var user = this.userService.GetUserByAccount(account.AccountID);
            var photoList = this.userService.GetPhotos(user.UserID);
            var bonus = this.partyService.GetBonus(User.Identity.Name);
            var bonusList = this.partyService.GetBonusLog(User.Identity.Name, page ?? 0, 10);
            UserCenterPageView pageView = new UserCenterPageView();
            pageView.Account = account;
            pageView.User = user;
            pageView.User.Birthday = DateTime.Parse(pageView.User.Birthday.Value.ToShortDateString()).Date;
            pageView.UserPhotos = photoList;
            BonusPageView bonusView = new BonusPageView();
            bonusView.Bonus = bonus;
            bonusView.Log = bonusList;
            pageView.BonusView = bonusView;

            if (!string.IsNullOrEmpty(user.Location))
            {
                string[] nativeArray = user.Location.Split(' ');
                CountrySelectionPageView nativeView = new CountrySelectionPageView();
                if (nativeArray != null && nativeArray.Count() == 3)
                {

                    nativeView.SelectedProvince = nativeArray[0];
                    nativeView.SelectedCity = nativeArray[1];
                    nativeView.SelectedZone = nativeArray[2];
                }
                else if (nativeArray != null && nativeArray.Count() == 2)
                {
                    nativeView.SelectedProvince = nativeArray[0];
                    nativeView.SelectedCity = nativeArray[1];
                }
                else
                {
                    nativeView.SelectedProvince = nativeArray[0];
                }
                ViewData["CurrentLocation"] = nativeView;
            }
            else
            {
                ViewData["CurrentLocation"] = new CountrySelectionPageView();
            }


            if (!string.IsNullOrEmpty(user.NativePlace))
            {
                string[] nativeArray = user.NativePlace.Split(' ');
                NativeSelectionPageView nativeView = new NativeSelectionPageView();
                if (nativeArray != null && nativeArray.Count() == 3)
                {

                    nativeView.SelectedNativeProvince = nativeArray[0];
                    nativeView.SelectedNativeCity = nativeArray[1];
                    nativeView.SelectedNativeZone = nativeArray[2];
                }
                else if (nativeArray != null && nativeArray.Count() == 2)
                {
                    nativeView.SelectedNativeProvince = nativeArray[0];
                    nativeView.SelectedNativeCity = nativeArray[1];
                }
                else
                {
                    nativeView.SelectedNativeProvince = nativeArray[0];
                }
                ViewData["CurrentNative"] = nativeView;
            }
            else
            {
                ViewData["CurrentNative"] = new NativeSelectionPageView();
            }
        
            return View(pageView);

        }

        [HttpGet]
        [UserAuthorize]
        public ActionResult UserEdit(int id)
        {
            
            var user = this.userService.GetUser(id);
            if (!string.IsNullOrEmpty(user.Location))
            {
                string[] nativeArray = user.Location.Split(' ');
                LocationSelectionPageView nativeView = new LocationSelectionPageView();
                if (nativeArray != null && nativeArray.Count() == 3)
                {

                    nativeView.SelectedProvince = nativeArray[0];
                    nativeView.SelectedCity = nativeArray[1];
                    nativeView.SelectedZone = nativeArray[2];
                }
                else if (nativeArray != null && nativeArray.Count() == 2)
                {
                    nativeView.SelectedProvince = nativeArray[0];
                    nativeView.SelectedCity = nativeArray[1];
                }
                else
                {
                    nativeView.SelectedProvince = nativeArray[0];
                }
                ViewData["CurrentLocation"] = nativeView;
            }
            else
            {
                ViewData["CurrentLocation"] = new LocationSelectionPageView();
            }


            if (!string.IsNullOrEmpty(user.NativePlace))
            {
                string[] nativeArray = user.NativePlace.Split(' ');
                NativeSelectionPageView nativeView = new NativeSelectionPageView();
                if (nativeArray != null && nativeArray.Count() == 3)
                {

                    nativeView.SelectedNativeProvince = nativeArray[0];
                    nativeView.SelectedNativeCity = nativeArray[1];
                    nativeView.SelectedNativeZone = nativeArray[2];
                }
                else if (nativeArray != null && nativeArray.Count() == 2)
                {
                    nativeView.SelectedNativeProvince = nativeArray[0];
                    nativeView.SelectedNativeCity = nativeArray[1];
                }
                else
                {
                    nativeView.SelectedNativeProvince = nativeArray[0];
                }
                ViewData["CurrentNative"] = nativeView;
            }
            else
            {
                ViewData["CurrentNative"] = new NativeSelectionPageView();
            }
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            return PartialView("_UserEdit", user);
        }

        [HttpPost]
        [UserAuthorize]
        public ActionResult UserEdit(User user, LocationSelectionPageView cuountryView, NativeSelectionPageView nativeView ,HttpPostedFileBase uploadFile, FormCollection collection)
        {
            if (user == null)
            {
                throw new ArgumentNullException("Item cannot be null!");
            }

            if (uploadFile != null)
            {
                if (!imageType.Contains(uploadFile.ContentType))
                {
                    ModelState.AddModelError("Photo", "图片类型不允许!");
                    Response.StatusCode = 500;
                    return Content("只允许上传JPEG格式的图片");
                    //return View();
                }

                if (uploadFile.ContentLength / 1024 / 1024 > 4)
                {
                    ModelState.AddModelError("Photo", "上传图片大小不允许超过4MB");
                    Response.StatusCode = 500;
                    return Content("上传图片大小不允许超过4MB");

                }

            }
            try
            {
                if (uploadFile != null)
                {
                    string parentPath = @"~/Files/Photos/" + user.UserID.ToString() + "/";
                    string titlePath = @"~/Files/Photos/" + user.UserID.ToString() + "/Title/";
                    if (!Directory.Exists(Server.MapPath(titlePath)))
                    {
                        Directory.CreateDirectory(Server.MapPath(titlePath));
                    }

                    string title = Path.GetRandomFileName() + ".jpg";
                    user.Photo = title;
                   
                    Image.MakeThumbnailImg(uploadFile, this.Server.MapPath(titlePath + title), 79, 79);
                    // Generate image for party
                    Image.MakeThumbnailImg(uploadFile, this.Server.MapPath(parentPath + title), 70, 90);

                }
                string location = (cuountryView.SelectedProvince + " " + cuountryView.SelectedCity + " " + cuountryView.SelectedZone).Trim();
                if (!string.IsNullOrEmpty(location))
                {
                    user.Location = location;
                }
                string native = (nativeView.SelectedNativeProvince + " " + nativeView.SelectedNativeCity + " " + nativeView.SelectedNativeZone).Trim();
                if (!string.IsNullOrEmpty(native))
                {
                    user.NativePlace = native;
                }


                this.userService.UpdateUser(user);
                // ModelState.Clear();

                return Content("");

            }
            catch (Exception)
            {
                //ViewData["CurrentLocation"] = new CountrySelectionPageView();
                //ViewData["CurrentNative"] = new NativeSelectionPageView();
                ModelState.AddModelError("", "更新过程中出现异常，请重试！");
                Response.StatusCode = 500;
                return Content("更新异常！");
            }
        }

        [HttpPost]
        [UserAuthorize]
        public ActionResult Edit(User user, CountrySelectionPageView cuountryView, NativeSelectionPageView nativeView, HttpPostedFileBase uploadFile, FormCollection collection)
        {
            if (user == null)
            {
                throw new ArgumentNullException("Item cannot be null!");
            }

            if (uploadFile != null)
            {
                if (!imageType.Contains(uploadFile.ContentType))
                {
                    ModelState.AddModelError("Photo", "图片类型不允许!");
                    //return View();
                }

                if (uploadFile.ContentLength / 1024 / 1024 > 4)
                {
                    ModelState.AddModelError("Photo", "上传图片大小不允许超过4MB");
 
                }

            }

            //user.Gender = (collection["Gender"].ToString() == "0") ? false : true;
            //user.Marriage = (collection["Marriage"].ToString() == "0") ? false : true;

            // Upload file
            //string directory = Server.MapPath("~/Files/Photos/" + User.Identity.Name);
            //string path = directory + "/" + Path.GetFileName(uploadFile.FileName);
            //user.Photo = User.Identity.Name + "/" + Path.GetFileName(uploadFile.FileName);

            //if (!Directory.Exists(directory))
            //{
            //    Directory.CreateDirectory(directory);
            //}
            //uploadFile.SaveAs(path);
            // Image.GenerateThumbnail(path, directory + "/small/" + Path.GetFileName(uploadFile.FileName), 45, 45);
            try
            {
                if (uploadFile != null)
                {
                    string parentPath = @"~/Files/Photos/" + user.UserID.ToString() + "/";
                    string titlePath = @"~/Files/Photos/" + user.UserID.ToString() + "/Title/";
                    if (!Directory.Exists(Server.MapPath(titlePath)))
                    {
                        Directory.CreateDirectory(Server.MapPath(titlePath));
                    }
                    string title = Path.GetRandomFileName() + ".jpg";
                    user.Photo = title;

                    Image.MakeThumbnailImg(uploadFile, this.Server.MapPath(titlePath + title), 79, 79);

                    Image.MakeThumbnailImg(uploadFile, this.Server.MapPath(parentPath + title), 70, 90);
                }
                string location = (cuountryView.SelectedProvince + " " + cuountryView.SelectedCity + " " + cuountryView.SelectedZone).Trim();
                if (!string.IsNullOrEmpty(location))
                {
                    user.Location = location;
                }

                string native = (nativeView.SelectedNativeProvince + " " + nativeView.SelectedNativeCity + " " + nativeView.SelectedNativeZone).Trim();
                if (!string.IsNullOrEmpty(native))
                {
                    user.NativePlace = native;
                }
                this.userService.UpdateUser(user);
                // ModelState.Clear();

                return RedirectToAction("UserCenter");
   
            }
            catch (Exception)
            {
                //ViewData["CurrentLocation"] = new CountrySelectionPageView();
                //ViewData["CurrentNative"] = new NativeSelectionPageView();
                ModelState.AddModelError("", "更新过程中出现异常，请重试！");
                var account = this.userService.GetAccount(User.Identity.Name);
                var users = this.userService.GetUserByAccount(account.AccountID);
                var photoList = this.userService.GetPhotos(user.UserID);
                var bonus = this.partyService.GetBonus(User.Identity.Name);
                var bonusList = this.partyService.GetBonusLog(User.Identity.Name, 0, 20);
                UserCenterPageView pageView = new UserCenterPageView();
                pageView.Account = account;
                pageView.User = users;
                pageView.UserPhotos = photoList;
                BonusPageView bonusView = new BonusPageView();
                bonusView.Bonus = bonus;
                bonusView.Log = bonusList;
                pageView.BonusView = bonusView;
                return View("UserCenter", pageView);
            }

        }

        [HttpGet]
        [UserAuthorizeAttribute]
        public ActionResult PhotoView(int? id)
        {
            var photo = this.userService.GetPhoto(id ?? 0);
            return View(photo);
        }



        [HttpPost]
        [UserAuthorize]
        public ActionResult Upload(HttpPostedFileBase uploadFile, FormCollection collection, int id, string[] checkedid)
        {
            if (collection["hdIsDelete"] != null && collection["hdIsDelete"].ToString() == "True" || (checkedid != null && checkedid.Count() > 0))
            {
                if (checkedid != null && checkedid.Count() > 0)
                {

                    foreach (var item in checkedid)
                    {

                        this.userService.RemovePhoto(int.Parse(item));
                        
                    }
                }
                var list = this.userService.GetPhotos(id);
                return View("_Photo", list);
            }
            else
            {


                if (uploadFile == null)
                {
                    ModelState.AddModelError("Photo", "Photo Cannot be null!");
                    return Content("请选择要上传的照片");
                    
                }

                if (!imageType.Contains(uploadFile.ContentType))
                {
                    ModelState.AddModelError("Photo", "Invalidate type!");
                    return Content("您上传的照片格式不符合要求,请上传jpg格式的图片");
                }

                if(uploadFile.ContentLength /1024/1024 > 4)
                {
                    ModelState.AddModelError("Photo", "Invalidate type!");
                    return Content("照片大小请不要超过4MB");
                }

                string parentDir = Server.MapPath("~/Files/Photos/" + id + "/Album/");
                string subDir = Server.MapPath("~/Files/Photos/" + id + "/Album/Thumb/");
                // string path = directory + "/" + Path.GetFileName(uploadFile.FileName);
                string photoName = Path.GetRandomFileName() + ".jpg";
                Photo photo = new Photo
                {
                    IsMain = false,
                    UserID = id,
                    Desc = string.Empty,
                    Url = photoName,
                    CreateDate = DateTime.Now
                };
                try
                {
                    this.userService.AddPhoto(photo);
                    if (!Directory.Exists(parentDir))
                    {
                        Directory.CreateDirectory(parentDir);
                        if (!Directory.Exists(subDir))
                        {
                            Directory.CreateDirectory(subDir);
                        }
                    }

                    // uploadFile.SaveAs(parentDir + photoName);
                    Image.MakeThumbnailImg(uploadFile, parentDir + photoName, 720, 540);

                    Image.MakeThumbnailImg(uploadFile, subDir + photoName, 170, 128);
                   


                }
                catch (PhotoEnoughException ex)
                {

                    //ModelState.AddModelError("", "用户最多允许上传四张相片");
                    Response.StatusCode = 500;
                    return Content("用户最多允许上传四张相片");
                }

                var photoList = this.userService.GetPhotos(id);
                return View("_Photo", photoList);
            }

        }

        [HttpGet]
        public ActionResult TopUserList()
        {
            // var list = this.userService.ShowBillBoard();
            IEnumerable<DLM.Domain.DTO.BillBoard> list = PageDataService.BillboardList();
            return View(list);
        }

        [HttpPost]
        public ActionResult SearchUser(FormCollection collection)
        {

            string type = collection["hdUserSearchType"] == null ? "全部" : collection["hdUserSearchType"].ToString();
            string content = collection["txtSearch"] == null ? string.Empty : collection["txtSearch"].ToString();
            //this.userService.SearchUser(Server.HtmlEncode(type),Server.HtmlEncode(content),)
            switch (type.Trim())
            {
                case "全部":
                    type = "0";
                    break;
                case "昵称":
                    type = "1";
                    break;
                case "籍贯":
                    type = "2";
                    break;
                case "性别":
                    type = "3";
                    break;
                case "年龄":
                    type = "4";
                    break;
                default:
                    type = "0";
                    break;
            }
            return RedirectToAction("SearchUser", new { type = Server.HtmlEncode(type), para = Server.HtmlEncode(content) });
            //return Redirect(Server.HtmlEncode("~/User/SearchUser?type=" + type + "&para=" + content));
        }

        [HttpGet]
        public ActionResult SearchUser(int? pageIndex, string type, string para)
        {
            try
            {
                if (string.IsNullOrEmpty(type))
                {
                    type = Request.QueryString["type"] == null ? string.Empty : Request.QueryString["type"].ToString();
                }
                if (string.IsNullOrEmpty(para))
                {
                    para = Request.QueryString["para"] == null ? string.Empty : Request.QueryString["para"].ToString();
                }
                var list = this.userService.SearchUser(Server.HtmlEncode(type), Server.HtmlEncode(para), pageIndex ?? 0, 10);
                return View(list);
            }
            catch (Exception ex)
            {
                LoggingFactory.GetLogger().Error(ex.Message, ex);
                return View("Error");
            }
     
        }

        [UserAuthorize]
        public ActionResult MessageCenter(int? messageid, int? noticeid)
        {
            int pageIndex;
            int.TryParse(Request.QueryString["noticeid"], out pageIndex);

            MessagePageView messageView = new MessagePageView();
            var messageList = this.userService.GetMessage(User.Identity.Name, messageid ?? 0, 10);
            messageView.Messages = messageList;
            var noticeList = this.userService.GetNotice(pageIndex, 10);
            messageView.Notices = noticeList;
            if (Request.IsAjaxRequest())
            {
                if (messageid != null)
                {
                    return View("_MyMessage", messageView.Messages);
                }
                if (noticeid != null)
                {
                    return View("_MyNotice", messageView.Notices);
                }
            }
            return View(messageView);
        }

        [HttpGet]
        [UserAuthorize]
        public ActionResult MessageView(int? id)
        {
            var message = this.userService.GetMessage(id ?? 0);
            return View(message);
        }

        [HttpPost]
        [UserAuthorize]
        public ActionResult ConfirmedMessage(int id)
        {
            if (Request.IsAjaxRequest())
            {
                this.userService.ConfirmeMessage(id);
            }
            return View();
        }

        [HttpGet]
        [UserAuthorize]
        public ActionResult NoticeView(int? id)
        {
            var notice = this.userService.GetNotice(id ?? 0);
            return View(notice);
        }


        [HttpPost]
        [UserAuthorize]
        public ActionResult DeleteMessage(FormCollection collection, string[] checkedid)
        {
            if (checkedid != null && checkedid.Count() > 0)
            {
                foreach (var item in checkedid)
                {

                    this.userService.DeleteMessage(int.Parse(item));
                }
            }
            var list = this.userService.GetMessage(User.Identity.Name, 0, 10);
            return View("_MyMessage", list);

        }

        [HttpPost]
        [UserAuthorize]
        public ActionResult DeletePhoto(int id)
        {
            this.userService.RemovePhoto(id);
            var list = this.userService.GetPhotos(id);
            return View("_Photo", list);
        }

        [UserAuthorize]
        public ActionResult GetAlbum(int id)
        {
            if (Request.IsAjaxRequest())
            {
                var list = this.userService.GetPhotos(id);
                return PartialView("_Photo", list);
            }
            return View();
        }

    }
}
